import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class ThemeProvider extends ChangeNotifier {
  ThemeMode _themeMode = ThemeMode.light; // 默认亮色

  ThemeMode get themeMode => _themeMode;

  ThemeProvider(){
    _loadTheme();
  }

  // 从 SharedPreferences 加载主题
  Future<void> _loadTheme() async {
    final prefs = await SharedPreferences.getInstance();
    if (!prefs.containsKey('themeMode')) {
      await prefs.setString('themeMode', 'light');
    }
    final savedMode = prefs.getString('themeMode') ?? 'light';
    _themeMode = _stringToThemeMode(savedMode);
    notifyListeners();
  }

  // 保存主题到 SharedPreferences
  Future<void> saveTheme(ThemeMode mode) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('themeMode', _themeModeToString(mode));
    _themeMode = mode;
    // print(mode);
    notifyListeners();
  }

  // 切换主题（带持久化）
  void toggleTheme(BuildContext context) {
    ThemeMode newMode;
    switch (_themeMode) {
      case ThemeMode.light:
        newMode = ThemeMode.dark;
        break;
      case ThemeMode.dark:
        newMode = ThemeMode.system;
        break;
      default:
        newMode = ThemeMode.light; // 系统模式时默认切换为亮色
    }
    saveTheme(newMode);
  }

  // 工具方法：字符串转ThemeMode
  ThemeMode _stringToThemeMode(String str) {
    switch (str) {
      case 'light': return ThemeMode.light;
      case 'dark': return ThemeMode.dark;
      default: return ThemeMode.system;
    }
  }

  // 工具方法：ThemeMode转字符串
  String _themeModeToString(ThemeMode mode) {
    switch (mode) {
      case ThemeMode.light: return 'light';
      case ThemeMode.dark: return 'dark';
      default: return 'system';
    }
  }
}